import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

/**
 * transform params of http requests
 */
@Injectable()
export class SetParamInterceptor implements HttpInterceptor {
    constructor() { }

    // object2params(obj) {
    //     if (obj) {
    //         return Object.keys(obj).map(x => {
    //             let val = obj[x];
    //             if (typeof val !== 'string') {
    //                 val = JSON.stringify(val);
    //             }
    //             return x + '=' + val;
    //         }).join('&');
    //     }
    //     return '';
    // }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // DEMO:1
        const headers = req.headers
            .set('Content-Type', 'application/json');
        const authReq = req.clone({ headers });
        return next.handle(authReq);

        // DEMO:2
        // const headers = req.headers
        //     .set('Content-Type', 'application/x-www-form-urlencoded');
        // let body = null;
        // let params = null;
        // if (req.method === 'POST') {
        //     body = this.object2params(req.body);
        // } else if (req.method === 'GET') {
        //     params = req.params.append('date', new Date().getTime() + '');
        // }
        // const newReq = req.clone({
        //     headers: headers,
        //     body: body,
        //     params: params
        // });
        // return next.handle(newReq);
    }
}

export const HttpSetParamProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: SetParamInterceptor,
    multi: true
};